<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #hiddenMy{
            position: fixed;
            top: 0;
            left: 0;
            width: auto;
            height: auto;
            z-index: -100;
        }

    </style>
</head>
<body>
<div id="hiddenMy">
    <div>
        <image id="imageMy" style="visibility: visible;background-color: red;width: 100px;height: 100px"></image>
    </div>
    <video id="videoMy" autoplay muted style="visibility: visible;"></video>
    <canvas id="canvasMy" width="500px" height="500px" style="visibility: visible;;"></canvas>
    <button id="close" onclick="closeCam()">关闭摄像头</button>
</div>
</body>
<script src="https://code.jquery.com/jquery.min.js"></script>
<script>
    //参考连接：https://cloud.tencent.com/developer/article/1641490
//async 函数可能包含 0 个或者多个 await 表达式。await 表达式会暂停整个 async 函数的执行进程并出让其控制权
    let videoStream
    permission = true;

    //async函数不会阻塞程序，如果调用async函数中需要修改一些其他程序
    //需要使用的变量，一定要在.then(执行async函数后，接着执行的代码)中执行执行代码，不然后果自负
                openVideoStream().then(result=>{
                    ///每隔一秒照一次
                    if(permission) {
                        //别加let、var之类的，可能跟这个该死的js的局部变量和全局变量声明方式有关
                        interVal = setInterval(takePhoto, 400)
                    }
                    else{
                        console.log("未授权")
                    }
                })

    async function openVideoStream() {
        const defaultCon={
            video:true
        }
        const constraintsForWindows = {
            video: {
                width: {
                    min: 1280,
                    ideal: 1920,
                    max: 2560,
                },
                height: {
                    min: 720,
                    ideal: 1080,
                    max: 1440,
                },
            },
        };
        //要访问后置摄像头，我们必须在视频规格中包括 faceModeMode:"environment"
        //默认值为 faceingMode:"user"，即前置摄像头
        const constraintsForPhone={
            video: {
                width: {  min: 1280,
                    ideal: 1920,
                    max: 2560, },
                height: {  min: 720,
                    ideal: 1080,
                    max: 1440,},
                facingMode: "user"
            },
        }
        /*查看页面是否支持相机API*/
        if ("mediaDevices" in navigator && "getUserMedia" in navigator.mediaDevices) {
            try
            {
                const video=document.querySelector("#videoMy")
                //async和await成对使用，只能将一个函数定义为async,才能在里面使用await关键子，
                // 等待await后面修饰的函数执行完成后才可以执行下一步
                videoStream =await  navigator.mediaDevices.getUserMedia(defaultCon);//需要用户授权
                video.srcObject= videoStream
                //设置了autoplay就不用调用这个函数
                //video.play()
                //在这里直接调用照相的函数不行
            }
            catch (e) {
                permission=false
                console.log(e)
            }
        }
        else
        {
            permission=false
            alert("不支持")
        }
    }
    function takePhoto() {
        //尝试照相并保存：
        const video=document.querySelector("#videoMy")
        //将video当前帧画到canvas上，而后将图片转换成base64格式
        let canvas=document.querySelector("#canvasMy")
        let ctx=canvas.getContext("2d")
        ctx.drawImage(video,0,0,500,500)
        // toDataURL:可传入参数：'image/png'(默认)或'image/jpeg'
        let img = document.querySelector("#canvasMy").toDataURL("image/jpeg");
        // 这里的img就是得到的图片(base64格式)
       // document.getElementById('imageMy').src=img;
        //img.replace(/^data:image\/(png|jpg);base64,/,"")
    }
    function closeCam() {
            try {
                videoStream.getTracks().forEach(function (track) {
                    if (track.readyState == 'live') {
                        track.stop()
                    }
                })
            }
            catch (e)
            {
                console.log("关闭摄像头失败:"+e.toString())
                clearInterval(interVal)
            }
    }
</script>
</html>